const Router = require('koa-router');
const StudentRouter = new Router();
const StudentService = require('../service/StudentService');
const R = require('../utils/R');
const { isNull } = require('../utils/validators');
const Validators = require('../utils/validators');

StudentRouter.prefix('/api/v1/student');

/**
 * pageNum  页数
 * pageSize  一页的数据量
 */
StudentRouter.get('/list',async (ctx, next) => {
    let { pageSize, pageNum } = ctx.request.query;
    Validators.isNull(pageSize, 'pageSize').isNull(pageNum, 'pageNum');
    let data = await StudentService.findAll(pageSize, pageNum);
    ctx.body = R.okData(data);
})

/**
 * user_id 学生ID
 */
StudentRouter.get('/info', async (ctx, next) => {
    let {userId} = ctx.request.query;
    Validators.isNull(userId, 'userId');
    let data = await StudentService.findAttrById(userId);
    ctx.body = R.okData(data);
})

StudentRouter.post('/register', async (ctx, next) => {
    let user = ctx.request.body;
    Validators.isNull(user.username, 'username').isNull(user.password, 'password').isNull(user.nickname, 'nickname')
    .isNull(user.sex, 'sex').isHave(user.sex, [1, 2], 'sex').isNull(user.studentId, 'studentId').isNull(user.class, 'class')
    isNull(user.academyId, 'academyId').isNull(user.joinTime, 'joinTime');
    await StudentService.saveStudent(user);
    ctx.body = R.okMsg('注册用户成功');
})

StudentRouter.post('/delete', async (ctx, next) => {
    let user = ctx.request.body;
    Validators.isNull(user.userId, 'userId')
    await StudentService.deleteStudent(user.userId);
    ctx.body = R.okMsg('删除成功')
})

StudentRouter.post('/login', async (ctx, next) => {
    let user = ctx.request.body;
    Validators.isNull(user.username, 'username').isNull(user.password, 'password')
    let data = await StudentService.login(user);
    if(data.name || data == 0){
        ctx.body = R.errorMsg(data.name)
    }else {
        if(data == 210) ctx.body = R.error(data, '用户不存在')
        else if(data == 211) ctx.body = R.error(data, '密码错误')
        else ctx.body = R.okData(data)
    }
})

StudentRouter.post('/update', async (ctx, next) => {
    let user = ctx.request.body;
    Validators.isNull(user.nickname, 'nickname')
    .isNull(user.sex, 'sex').isHave(user.sex, ['1', '2'], 'sex').isNull(user.studentId, 'studentId').isNull(user.class, 'class')
    isNull(user.academyId, 'academyId').isNull(user.joinTime, 'joinTime').isNull(user.userId, 'userId');
    await StudentService.updateStudent(user);
    ctx.body = R.okMsg('修改成功')
})

StudentRouter.post('/password', async (ctx, next) => {
    let user = ctx.request.body;
    Validators.isNull(user.newPassword, 'newPassword').isNull(user.userId, 'userId').isNull(user.oldPassword, 'oldPassword');
    await StudentService.updatePassword(user);
    ctx.body = R.okMsg('修改密码成功')
})

module.exports = StudentRouter